package cn.jtcoding.springframework.core.factory;

import cn.jtcoding.springframework.core.annotation.Component;
import cn.jtcoding.springframework.core.annotation.Service;

import java.lang.annotation.Annotation;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public interface AliasBeanFactory extends BeanFactory {

    Map<String, String> aliasMap = new ConcurrentHashMap<>(16);

    default void setAliasName(String className, String aliasName) {
        aliasMap.put(className, aliasName);
    }

    default String getAliasName(Annotation[] annotations, String beanName) {
        if (annotations == null || annotations.length == 0) {
            throw new IllegalArgumentException("[ " + beanName + " ] annotation cannot be empty.");
        }

        String aliasName = beanName;
        for (Annotation annotation : annotations) {
            if (annotation instanceof Service) {
                String value = ((Service) annotation).value();
                if (!value.isEmpty()) {
                    aliasName = value;
                    break;
                }
            }

            if (annotation instanceof Component) {
                String value = ((Component) annotation).value();
                if (!value.isEmpty()) {
                    aliasName = value;
                    break;
                }
            }
        }
        return aliasName;
    }
}
